#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
#sys._getframe().f_back.f_code.co_name
import os
import math
from engine.uitls import *
global checkType
global SNO
import aircv as ac
import  random
import pymysql.cursors
import pymysql
import pandas as pd
import emoji
import urllib
import urllib3
import requests
import os
import time
import aircv as ac
from PIL import Image
import sys
import datetime
import math
import time
import hashlib
import json
import cv2
import numpy as np
import pickle
import screenRecog.build_features as bf
from screenRecog.trainer import ERFTrainer
import imghdr
import re
import random
Image.LOAD_TRUNCATED_IMAGES = True
#com.sankuai.meituan/com.meituan.android.pt.homepage.activity.MainActivity
#com.tencent.wework.launch.WwMainActivity
appDict = {'启动企业微信package': "com.tencent.wework",
           '启动美团package': "com.sankuai.meituan",
           '启动淘宝联盟package': "com.alimama.moon",
           "启动微信package": "com.tencent.mm",
           "启动淘宝package": "com.taobao.taobao",
           '启动淘宝联盟launch': ".ui.WizardActivity",
           "启动微信launch": ".ui.LauncherUI",
           "启动美团launch": "com.meituan.android.pt.homepage.activity.MainActivity",
           "启动淘宝launch": ".TBMainActivity",
           "启动企业微信launch": "com.tencent.wework.launch.LaunchSplashActivity"}
SNO=" "
LineSNO=""
handsetType=""
ErrorCount = 0
diguiCount = 0
def setErrorCountAdd():
    global ErrorCount
    print("设置ErrorCount 加加")
    ErrorCount = ErrorCount +1
    print(ErrorCount)
def setErrorCountZero():
    global ErrorCount
    global diguiCount
    ErrorCount = 0
    diguiCount = 0
    print("清零ErrorCount")
def getErrorCount():
    global ErrorCount

    print(ErrorCount)
    return ErrorCount


def setHandsetConnectByLine(handsetSno):
    global LineSNO
    LineSNO = handsetSno

def setHandsetSno(handsetSno):
    global SNO
    SNO = handsetSno
def setHandsetType(typex):
    global HANDSETTYPE
    HANDSETTYPE = typex
    global  handsetType
    handsetType = typex
def getHandsetType():
    global handsetType
    return  handsetType
def getHandsetSno():
    global SNO
    return  SNO

def getAdbPath():
    if sys.platform == "darwin":
        adbpath = "/usr/local/bin/adb "
    else:
        adbpath = "/usr/bin/adb "
    return adbpath

#debug for all filesf

def debugInfo(info, delay = 0,type="info"):
    info = str(info)
    timeTag = "[" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + "]"+info
    #print(timeTag)
    # print(timeTag + "[" + type + "]" +funcName+":" + info + "\n")
    # print("--- current function is      ", sys._getframe().f_code.co_name)
    # print("--- current function from ", sys._getframe().f_code.co_filename)
    # print("--- called by function      ", sys._getframe().f_back.f_code.co_name)
    # print("--- called at line               ", sys._getframe().f_back.f_lineno)
    tail = "    --- called from file:"+sys._getframe().f_back.f_code.co_filename.replace(os.getcwd(),"")+" func:"+sys._getframe().f_back.f_code.co_name+" ln:"+str(sys._getframe().f_back.f_lineno)
    print(timeTag+tail)
    if os.path.exists(os.getcwd()+"/debug.txt"):
        with open(os.getcwd()+"/debug.txt" )as f:
            filterFile = f.read()
        if sys._getframe().f_back.f_code.co_filename.replace(os.getcwd(),"") in filterFile:
            #如果debug.txt 里面 含有 这个文件的路径，那么这个文件被排除在屏幕显示的debug信息了
            print("ignore displayed on screen："+sys._getframe().f_back.f_code.co_filename.replace(os.getcwd(),""))
            pass

        else:
            cmd = getAdbPath()+" -s " + str(SNO) + "  shell am startservice com.qianteng.testcliper/.ClipboardService >"+getHandsetFileSavePath("/temp/ClipboardService.txt")
            os.system(cmd)
            cmd = getAdbPath()+" -s " + str(SNO) + " shell am broadcast -a clipper.info -e text " + "\"" + info + "\"" +"  -f 0x01000000 >"+getHandsetFileSavePath("/temp/broadcast.txt")
            os.system(cmd)
    else:
        #print("not debug mode")
        pass
    time.sleep(int(delay))


class ImageTagExtractor(object):
    def __init__(self, model_file, codebook_file):
        with open(model_file, 'rb') as f:
            self.erf = pickle.load(f)
        with open(codebook_file, 'rb') as f:
            self.kmeans, self.centroids = pickle.load(f)

    def predict(self, img, scaling_size):
        img = bf.resize_image(img, scaling_size)
        feature_vector = bf.BagOfWords().construct_feature(img, self.kmeans, self.centroids)
        image_tag = self.erf.classify(feature_vector)[0]
        return image_tag

def getToday():
    now = datetime.datetime.now()
    return now.strftime('%m-%d')

def getYestoday():
    now = datetime.datetime.now()
    delta = datetime.timedelta(days=1)
    yes=now - delta
    return yes.strftime("%m-%d")

def getWhatScreen(imgPath):
    ret = ""
    # model_file = './screenRecog/scerf.pkl'
    # codebook_file = './screenRecog/codebook.pkl'
    # input_image = cv2.imread(imgPath)
    # scaling_size = 200
    ret= ImageTagExtractor('./screenRecog/erf.pkl', './screenRecog/codebook.pkl').predict(cv2.imread(imgPath), 720)
    return ret
def waitForImagePull(current):
    currentSize = 0
    maxSize = 0
    maxRun = 0
    while 1:
        maxRun = maxRun + 1
        if maxRun > 50:
            print("wait hua er ye xie liao  50 times  ")
            return False
            break;
        try:

            time.sleep(0.6)
            if os.path.exists(current):
                # print("sleep a while for test file a.txt size change or not")
                time.sleep(0.6)
                # print(str(os.path.getsize(filePath)))
                maxSize = currentSize
                currentSize = os.path.getsize(current)
                if maxSize == currentSize and not maxSize == 0:
                    print("wait for image pull  times-----"+str(maxRun))
                    return True
                    break
            else:
                print("no " + current)
                return False
        except:
            print("system error - waitForImagePull fail-------------------------------")
            return False


#curl -F "filechoose=@/Users/guogarry/Downloads/c.jpg; "    http://192.168.0.107:8090/upload/?fname=c.jpg -m 90
def recogScreen(current):
    global SNO
    global ErrorCount
    global diguiCount
    retlist=[]
    if ErrorCount == 6:
        return retlist

    if not waitForImagePull(current):
        print("recogScreen wait image error")
        return

    img = cv2.imread(current,-1)


    height,width = img.shape[:2]
    size = (int(width*0.5),int(height*0.5))
    half = cv2.resize(img,size)
    cv2.imwrite(current+"half.png",half)
    cmd = 'curl -F "filechoose=@'+current+"half.png"+'; "'+  " http://192.168.0.107:8090/upload/?fname=c."+SNO+ ".png >"+getHandsetFileSavePath("/temp/curl.txt")
    os.system(cmd)
    with open(getHandsetFileSavePath("/temp/curl.txt"))as f:
        ret = f.read()
    #print(ret)
    try:
        retlist =eval(ret)
        #print(ret)
    except:
        x = 8*random.randint(1,5)

        print("图像识别服务出现错误递归进行下次 现在等待秒数"+str(x))
        time.sleep(x)
        setErrorCountAdd()
        diguiCount = diguiCount +1
        retlist = recogScreen(current)
        diguiCount = diguiCount - 1
        print("递归归来--"+str(diguiCount))
        #time.sleep(3)

        pass
    #print(retlist)
    if diguiCount == 0:
        for item in retlist:
            item[0][0] = item[0][0]*2
            item[0][1] = item[0][1] * 2
            item[0][2] = item[0][2] * 2
            item[0][3] = item[0][3] * 2
    print(retlist)
    return retlist

def adbRun(cmdString):
    global SNO
    cmd = getAdbPath()+" -s " + str(SNO) + " " + cmdString+" &>"+getHandsetFileSavePath("/temp/adbRun.txt")
    os.system(cmd)

def getOutFileCmd(filePath):
    global SNO
    ret = "python3 "+filePath+" " +getHandsetType()+" "+SNO+" "
    return ret

def getHandsetFileSavePath(filePath):
    global SNO
    basePath = os.getcwd() +"/shouji/" +getHandsetType()+"/"+SNO+"/"
    if (filePath.startswith('./')):
        tempPath = filePath.replace('./','/')
    else:
        tempPath = filePath


    if "*" in tempPath:
        tempPath = tempPath.split("*")[0]


    retPath = basePath+tempPath
    return retPath

def getHandsetXY():
    cmd = getAdbPath()+" -s " + str(SNO) + " " + "shell wm size"+" >"+getHandsetFileSavePath("/temp/xy.size")
    os.system(cmd)
    with open(getHandsetFileSavePath("/temp/xy.size"))as f:
        content = f.readline()
    content= content.split(':')[1].strip()
    content=content.split('x')
    return content[0],content[1]

def getHandsetTPXY():
    cmd = getAdbPath()+" -s " + str(SNO) + " " + "shell getevent -p|grep 0035"+" >"+getHandsetFileSavePath("/temp/tpxy.x")
    os.system(cmd)
    with open(getHandsetFileSavePath("/temp/tpxy.x"))as f:
        content = f.readline()
    content= content.split('max')[1].strip()
    contentx=content.split(',')


    cmd = getAdbPath()+" -s " + str(SNO) + " " + "shell getevent -p|grep 0036"+" >"+getHandsetFileSavePath("/temp/tpxy.x")
    os.system(cmd)
    with open(getHandsetFileSavePath("/temp/tpxy.x"))as f:
        content = f.readline()
    content= content.split('max')[1].strip()
    contenty=content.split(',')
    return contentx[0],contenty[0]

def convertPxyToRxy(x,y):
    hx,hy = getHandsetXY()
    tx,ty = getHandsetTPXY()
    x = x*hx/tx
    y = y*hy/ty
    return  x, y


def getTouchPos():
    cmd = getAdbPath()+" -s " + str(SNO) + " " + "shell getevent -c 20" \
                                                 ""+" >"+getHandsetFileSavePath("/temp/tppos.txt")

    debugInfo("pls touch this screen for get the xy,pos for calc dont touch and move others key or screen")
    os.system(cmd)
    print("get the pos now calc")
    os.system("cat "+getHandsetFileSavePath("/temp/tppos.txt")+"|grep '0003 0035'>"+getHandsetFileSavePath("/temp/tppos.x"))
    os.system("cat "+getHandsetFileSavePath("/temp/tppos.txt")+"|grep '0003 0036'>"+getHandsetFileSavePath("/temp/tppos.y"))
    with open(getHandsetFileSavePath("/temp/tppos.x"))as f:
        contentx = f.readline()
    contentx =contentx.split('0035')[1].strip()
    with open(getHandsetFileSavePath("/temp/tppos.y"))as f:
        contenty = f.readline()
    contenty =contenty.split('0036')[1].strip()
    x=int('0x'+contentx,16)
    y=int('0x'+contenty,16)
    debugInfo(str(x)+":"+str(y)+"pressed")
    return x,y

def getTouchPosRect(inputImg,tx,ty,saveImg):
    debugInfo("输入要截图的宽度 输入0 就跳过本次学习")
    x = input()
    if int(x) == 0:
        return 0
    print(x)
    debugInfo("输入要截图的高度 输入0 就跳过本次学习")
    y = input()
    print(y)
    if int(y) == 0:
        return 0
    im = Image.open(inputImg)
    xx = int(tx) - (int(x)/2)
    xx = int(xx) if int(xx)>0 else -int(xx)
    print( xx)
    yy = int(ty)- int(y)/2
    yy = int(yy) if int(yy)>0 else -int(yy)
    print(yy)
    xxw = int(tx)+(int(x)/2)
    yyh = int(ty)+(int(y)/2)
    print(xxw)
    print(yyh)
    maxx,maxy = getHandsetXY()
    xxw = int(maxx) if xxw> int(maxx) else xxw
    yyh = int(maxy) if yyh> int(maxy) else yyh
    box = (xx,yy,int(xxw),int(yyh))
    print(box)
    ng = im.crop(box)
    ng.save(saveImg)
    ng.show()
    debugInfo("是否需要重新学习，1  再来一次机会   ， 0 继续 ,2 重新执行本步骤 ")
    ret = input()
    if  1== int(ret):
        getTouchPosRect(inputImg,tx,ty,saveImg)
    elif 2 ==int(ret):
        return 2
    else:
        pass
    return 1

def matchImg(imgsrc, imgobj, confidenceSet=0.99):
    try:
        try:
            if imghdr.what(imgsrc) == "png":
                Image.open(imgsrc).convert("RGB").save(imgsrc)
            if imghdr.what(imgobj) == "png":
                Image.open(imgobj).convert("RGB").save(imgobj)
        except:
            print("matchImg   imghdr error")
            return (-2,-2)

        imsrc = ac.imread(imgsrc)
        imobj = ac.imread(imgobj)
        # find_all_sift  find_template
        match_result = ac.find_template(imsrc,
                                        imobj)  # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
        if match_result == None:
            debugInfo("没检测到任何结果")
            return (0, 0)
        else:
            pass
        print(match_result)
        if match_result["confidence"] > confidenceSet:
            return (int(match_result['result'][0]), int(match_result['result'][1]))
        else:
            debugInfo("有检测到结果，但是精度达不到要求"+str(confidenceSet))
            return (-1, -1)
    except RuntimeError:
        debugInfo("matchImgRuntime 错误")
        return (-2,-2)
        pass


def matchAllImg(imgsrc, imgobj, confidence=0.5):
    if not os.path.exists(imgsrc) or not os.path.exists(imgobj):
        debugInfo("matchImgRuntime matchAllImg 文件不存在错误")
        return (-1,-1)
    try:
        if imghdr.what(imgsrc) == "png":
            Image.open(imgsrc).convert("RGB").save(imgsrc)
        if imghdr.what(imgobj) == "png":
            Image.open(imgobj).convert("RGB").save(imgobj)
        imsrc = ac.imread(imgsrc)
        imobj = ac.imread(imgobj)
        # find_all_sift  find_template
        match_result = ac.find_all_template(imsrc,
                                            imobj)  # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
        if match_result == None:
            debugInfo("没检测到任何结果")
            return (0, 0)
        else:
            pass
        print(match_result)
    except RuntimeError:
        debugInfo("matchAllImgRuntime 错误")
        return (-1, -1)



def matchImgMinY(imgsrc, imgobj, confidence=0.99):
    debugInfo("获取最小Y匹配到图位置")
    if not os.path.exists(imgsrc) or not os.path.exists(imgobj):
        print("matchImg  file not exist error-----------" )
        return (-1,-1)
    try:
        if imghdr.what(imgsrc) == "png":
            Image.open(imgsrc).convert("RGB").save(imgsrc)
        if imghdr.what(imgobj) == "png":
            Image.open(imgobj).convert("RGB").save(imgobj)
        imsrc = ac.imread(imgsrc)
        imobj = ac.imread(imgobj)
        # find_all_sift  find_template
        match_result = ac.find_all_template(imsrc,
                                            imobj)  # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
        if match_result == None:
            return (0, 0)
        else:
            pass
        # print(match_result)
        minY = 0xffff
        minX = 0xffff
        # print(match_result)
        for x in match_result:
            if x["confidence"] > 0.99:
                if minY > x["result"][1]:
                    minY = x["result"][1]
                    minX = x["result"][0]
        return minX, minY
    except RuntimeError:
        debugInfo("matchImgMinY 错误")
        return (-1, -1)
        pass

def matchImgMinY2(imgsrc, imgobj, confidence=0.99):
    debugInfo("获取第二小Y匹配到图位置")
    if not os.path.exists(imgsrc) or not os.path.exists(imgobj):
        print("matchImg  file not exist error-----------" )
        return (-1,-1)
    try:
        if imghdr.what(imgsrc) == "png":
            Image.open(imgsrc).convert("RGB").save(imgsrc)
        if imghdr.what(imgobj) == "png":
            Image.open(imgobj).convert("RGB").save(imgobj)
        imsrc = ac.imread(imgsrc)
        imobj = ac.imread(imgobj)
        # find_all_sift  find_template
        match_result = ac.find_all_template(imsrc,
                                            imobj)  # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
        if match_result == None:
            return (0, 0)
        else:
            pass
        # print(match_result)
        minY = 0xffff
        minX = 0xffff
        print(match_result)
        newlist = []
        for x in match_result:
            if x["confidence"] > 0.99:
                if minY > x["result"][1]:
                    minY = x["result"][1]
                    minX = x["result"][0]
                    newlist.append(x)
                else:
                    newlist.append(x)
        for x in newlist:
            if minY == x["result"][1]:
                newlist.remove(x)
        minY = 0xffff
        for x in newlist:
            if minY > x["result"][1]:
                minY = x["result"][1]
        return minX, minY
    except RuntimeError:
        print("matchImg Runtime Error")
        return (-1, -1)
        pass

def matchImgMaxY(imgsrc, imgobj, confidence=0.99):
    debugInfo("获取最大Y匹配到图位置")
    if not os.path.exists(imgsrc) or not os.path.exists(imgobj):
        print("matchImg  file not exist error-----------" )
        return (-1,-1)
    try:
        if imghdr.what(imgsrc) == "png":
            Image.open(imgsrc).convert("RGB").save(imgsrc)
        if imghdr.what(imgobj) == "png":
            Image.open(imgobj).convert("RGB").save(imgobj)
        imsrc = ac.imread(imgsrc)
        imobj = ac.imread(imgobj)
        # find_all_sift  find_template
        match_result = ac.find_all_template(imsrc,
                                            imobj)  # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
        if match_result == None:
            return (0, 0)
        else:
            pass
        maxY = 0
        maxX = 0
        # print(match_result)
        for x in match_result:
            if x["confidence"] > 0.99:
                if maxY < x["result"][1]:
                    maxY = x["result"][1]
                    maxX = x["result"][0]
        return maxX, maxY
    except RuntimeError:
        print("matchImg Runtime Error")
        return (-1, -1)
        pass

def launchApp(appName, delay=1, forceClose=1):
    debugInfo(appName)
    package = appDict[appName + 'package']
    launch = appDict[appName + 'launch']
    if forceClose == 1:
        os.system(getAdbPath()+" -s " + str(SNO) + " "  + " shell am force-stop  " + package)
    else:
        pass
    os.system(getAdbPath()+" -s " + str(SNO) + " " +" shell am start -n  " + package + "/" + launch)
    time.sleep(delay)

def keyBackByKeyPress():
    debugInfo("KEYCODE_BACK pressed \n")
    os.system(getAdbPath()+" -s " + str(SNO) + " " +" shell input keyevent KEYCODE_BACK")

def touchSwipeScreen(posx, posy, posxx, posyy, timeswipe):
    debugInfo("touchSwipeScreen" + str(posx) + " " + str(posy) + " " + str(posxx) + " " + str(posyy) + " " + str(timeswipe))
    os.system(getAdbPath()+" -s "+str(SNO) + " shell input swipe " + str(posx) + " " + str(posy) + " " + str(posxx) + " " + str(posyy) + " " + str(timeswipe))


def AdbPullFromHandset(path,SNO):
    os.system(getAdbPath()+" -s "+str(SNO) + " pull  " + path)

def AdbShellRmFromHandset(path,SNO):
    os.system(getAdbPath()+" -s "+str(SNO) + " shell rm  " + path)

def touchTap(x,y):
    debugInfo('Action  点击坐标' + str(x) + ':' + str(y))
    if not x== -1:
        os.system(getAdbPath()+" -s "+str(SNO) + " shell input tap " + str(x) + " " + " " + str(y))

def touchTapDouble(x,y):
    debugInfo('Action  双击坐标' + str(x) + ':' + str(y))
    if not x == -1:
        os.system(getAdbPath()+" -s "+str(SNO) + " shell input tap " + str(x) + " " + " " + str(y))
        os.system(getAdbPath()+" -s "+str(SNO) + " shell input tap " + str(x) + " " + " " + str(y))


def swipeLeftToRight():
    debugInfo("从左到右滑动屏幕")
    x,y = getRealScreenSizeXY()
    touchX = str(int(x)/4)
    touchXEnd =str(int(x))
    touchY = str(int(y)/2)
    cmd = getAdbPath()+" -s  "+str(SNO) + " shell input swipe " + touchX + " " +touchY+ " " + touchXEnd+" "+touchY+" 500"
    os.system(cmd)


def swipeRightToLeft():
    debugInfo("从右往左滑动屏幕")
    x,y = getRealScreenSizeXY()
    touchX = str(int(x)/4)
    touchXEnd =str(int(x)-int(float(touchX)))
    touchY = str(int(y)/2)
    cmd = getAdbPath()+" -s  "+str(SNO) + " shell input swipe " + touchXEnd + " " +touchY+ " " + " 0 "+" "+touchY+" 500"
    os.system(cmd)

def touchLongpress(x,y):
    debugInfo('Action  长按坐标'+str(x)+':'+str(y))
    if not x==-1:
        os.system(getAdbPath()+" -s "+str(SNO) + " shell input swipe " + str(x) + " " + " " + str(y) + " " + str(x) + " " + " " + str(y) + " 3000")

def shotScreen(fileName="screen"):
    global SNO
    global LineSNO
    global handsetType
    if not os.path.exists(os.getcwd()+"/cut/"+handsetType):
        os.mkdir(os.getcwd()+"/cut/"+handsetType)
    if not os.path.exists(os.getcwd()+"/cut/"+handsetType+"/"+SNO):
        os.mkdir(os.getcwd()+"/cut/"+handsetType+"/"+SNO)
    cmd = getAdbPath()+" -s " + str(SNO) + " " + "shell screencap -p /sdcard/"+str(fileName)+".png  &&"
    #debugInfo(cmd)

    #os.system(cmd)
    time.sleep(2)
    sno = SNO
    if len(LineSNO)>4:
        sno = LineSNO
    cmd2 = getAdbPath()+" -s " + str(sno) + " " + " pull /sdcard/"+str(fileName)+".png  "+os.getcwd()+"/cut/"+handsetType+"/"+SNO +"/&>"+getHandsetFileSavePath("/temp/pull.txt")
    #debugInfo(cmd)
    cmd = cmd+cmd2
    os.system(cmd)
    time.sleep(2)

    filePath = os.getcwd()+"/cut/"+handsetType+"/"+SNO +"/current.png"

    #print(filePath)

    waitForImagePull(filePath)


    return os.getcwd()+"/cut/"+handsetType+"/"+SNO +"/"+str(fileName)+".png"


def onlyBack(type=handsetType,sno=SNO):
    print("返回上级 onlyBack called")
    cmd = getAdbPath() +" -s  "+ str(SNO) + " shell input keyevent KEYCODE_HOME"
    os.system(cmd)
def lightOnTheScreen(type=handsetType,sno=SNO):
    print("点亮屏幕 called")
    os.system(getAdbPath() +" -s  "+ str(SNO) + " shell input keyevent KEYCODE_POWER")
def lightOffTheScreen(type=handsetType,sno=SNO):
    print("点亮屏幕 called")

    os.system(getAdbPath() +" -s  "+ str(SNO) + " shell input keyevent KEYCODE_POWER")
def unlockTheScreen(type=handsetType,sno=SNO):

    print("点亮屏幕并解锁 called")
    lightOnTheScreen(type,sno)
    os.system(getAdbPath() +" -s  "+ str(SNO) + " shell input keyevent 82")
    os.system(getAdbPath() +" -s  "+ str(SNO) + " shell input keyevent KEYCODE_HOME")
def wakeupHandset():
    debugInfo("唤醒手机，如果是ip 调用 ： adb connect ip地址")
    if '.' in getHandsetSno():
        cmd = getAdbPath() + "connect " + getHandsetSno()
        os.system(cmd)


def isScreenOff():
    debugInfo("是否屏幕关闭  1 关闭，  0 屏幕开着")
    ret = True
    cmd = getAdbPath()+" -s " + str(SNO) + " shell dumpsys power|grep state=ON"+">"+getHandsetFileSavePath("/temp/powerON.txt")
    os.system(cmd)
    cmd = getAdbPath()+" -s " + str(SNO) + " shell dumpsys power|grep state=OFF"+">"+getHandsetFileSavePath("/temp/powerOFF.txt")
    os.system(cmd)
    if os.path.getsize(getHandsetFileSavePath("/temp/powerON.txt"))>4:
        debugInfo("not powerOFF")
        ret = False
    if os.path.getsize(getHandsetFileSavePath("/temp/powerOFF.txt"))>4:
        debugInfo("not powerON ")
    return  ret


def getRealScreenSizeXY():
    debugInfo("获取屏幕宽度高度")
    ret = True
    cmd = getAdbPath()+" -s  " + str(SNO) + " shell dumpsys window displays|grep DisplayFrames"+">"+getHandsetFileSavePath("/temp/getRealScreenSize.txt")
    if not os.path.exists(getHandsetFileSavePath("/temp/getRealScreenSize.txt")):
        os.system(cmd)
    with open(getHandsetFileSavePath("/temp/getRealScreenSize.txt")) as f:
        content = f.read()
    ret = content.strip().replace('=',' ').split(' ')
    try:
        x = ret[2]
        y = ret[4]
    except:
        return 720,1520
    return  x,y

def isReadyToRunTask():
    if isScreenOff():
        unlockTheScreen()
    else:
        onlyBack()
    #kill all app  tobe add to here
    os.system(getAdbPath()+" -s " + str(SNO) +  " shell am force-stop com.tencent.mm")

    debugInfo("准备要开始执行任务了",3)
def isRunTaskComplete():
    debugInfo("任务完成关闭屏幕了要",3)

    if isScreenOff():
        pass
    else:
        lightOffTheScreen()


def isHandsetConnected(msg,engine=""):
        retSno = getHandsetSno()
        if not os.path.exists(os.getcwd()+"/shouji/"+getHandsetType()):
            debugInfo("未适配的手机型号",4)
            time.sleep(100)
            return ""
        if not os.path.exists(os.getcwd() + "/cut/"):
            os.makedirs(os.getcwd() + "/cut/")
        if  not os.path.exists(getHandsetFileSavePath("/temp/")):
            os.makedirs(getHandsetFileSavePath("/temp/"))
        if not os.path.exists(getHandsetFileSavePath("temp/ip.txt")):
            cmd = getAdbPath() + " -s " + str(SNO) + " shell  ifconfig|grep Bcast >" + getHandsetFileSavePath(
                "/temp/ip.txt")
            os.system(cmd)
        else:
            if os.path.getsize(getHandsetFileSavePath("temp/ip.txt"))<5:
                cmd = getAdbPath() + " -s " + str(SNO) + " shell  ifconfig|grep Bcast >" + getHandsetFileSavePath("/temp/ip.txt")
                os.system(cmd)
        with open(getHandsetFileSavePath("/temp/ip.txt"))as f:
            ip = f.read()
        ip = ip.split(':')[1].split(" ")[0]

        if 1:
            cmd = getAdbPath() + " -s " + str(ip) + " shell  date '+%Y-%m-%d'>" + getHandsetFileSavePath(
                "/temp/today.txt")
            os.system(cmd)
            if os.path.getsize(
                    getHandsetFileSavePath("/temp/today.txt")) != 11:  # 简单判断 2020-xx-xx 加回车 11个字符 不是这个就是没连上了。
                debugInfo("设备没连接，我来--- ", 3)
                cmd = getAdbPath() + " -s " + str(SNO) + " tcpip 5555"
                os.system(cmd)
                time.sleep(1)
                cmd = getAdbPath() + "connect " + ip
                os.system(cmd)

        setHandsetSno(ip)
        retSno = ip



        if  not os.path.exists(getHandsetFileSavePath("/temp/")):
            os.makedirs(getHandsetFileSavePath("/temp/"))
        time.sleep(1)
        cmd = getAdbPath()+" -s " + str(SNO) + " shell  date '+%Y-%m-%d'>"+getHandsetFileSavePath("/temp/today.txt")
        os.system(cmd)
        cmd = getAdbPath()+" -s " + str(SNO) + " shell am start -n  com.qianteng.testcliper/.MainActivity"
        os.system(cmd)
        time.sleep(1)
        cmd = getAdbPath()+" -s " + str(SNO) + " shell am startservice com.qianteng.testcliper/.ClipboardService "
        os.system(cmd)
        time.sleep(1)
        randomText= str(random.randint(10,9999))
        #TODO:删除 联盟图片
        AdbShellRmFromHandset("/storage/emulated/0/Pictures/淘宝联盟/*.*", SNO)
        os.system("rm -rf  "+getHandsetFileSavePath("/temp/淘宝联盟"))

        AdbShellRmFromHandset("/storage/emulated/0/Pictures/WeiXin/*.*", SNO)
        os.system("rm -rf  "+getHandsetFileSavePath("/temp/WeiXin"))

        AdbShellRmFromHandset("/sdcard/tencent/MicroMsg/WeiXin/*.*", SNO)
        os.system("rm -rf  " + getHandsetFileSavePath("/temp/WeiXin"))
        inputMsgToHandset("快来哦亲们，记得发陶口令给我茶券"+randomText)
        ret = getMsgFromHandsetCliper()
        if randomText in ret:
            debugInfo("剪贴板自测通过",3)
        else:
            debugInfo("剪贴板自测不通过！！！！",4)

        if os.path.getsize(getHandsetFileSavePath("/temp/today.txt"))!=11:# 简单判断 2020-xx-xx 加回车 11个字符 不是这个就是没连上了。
            debugInfo("设备没连接，我过30秒在重试--- ",30)
            if '.' in getHandsetSno():
                cmd = getAdbPath() + "connect " + getHandsetSno()
                os.system(cmd)
                isHandsetConnected(msg)
        else:
            debugInfo("链接到这个设备: " +SNO,3)
        return  retSno


def inputMsgToHandset(msg):
    debugInfo("设置剪贴板内容")
    cmd = getAdbPath() +" -s  "+ str(SNO) + " shell am broadcast -a clipper.set  -e text "+"\""+msg+"\""  +" -f 0x01000000"
    os.system(cmd)
    print(cmd)


def getMsgFromHandsetCliper():
    debugInfo("获取剪贴板内容")
    cmd = getAdbPath() +" -s  "+ str(SNO) + " shell am broadcast -a clipper.get  -f 0x01000000>"+getHandsetFileSavePath("/temp/phoneClip.txt")
    os.system(cmd)
    print(cmd)
    with open(getHandsetFileSavePath("/temp/phoneClip.txt")) as f:
        content = f.read()
    contents = content.split("\"")
    if contents.__len__()>2:
        content = contents[1].strip()
    debugInfo(content,2)
    return content

def getAndSetMsgFromHandsetCliper(msg,SNO):
    debugInfo("获取并设置剪贴板内容",6)
    cmd = getAdbPath() +" -s  "+ str(SNO) + " shell am broadcast -a clipper.get -e text "+"\""+msg+"\""  +" -f 0x01000000>"+getHandsetFileSavePath("/temp/phoneClip.txt")
    os.system(cmd)
    print(cmd)
    with open(getHandsetFileSavePath("/temp/phoneClip.txt")) as f:
        content = f.read()
    contents = content.split("\"")
    if contents.__len__()>2:
        content = contents[1].strip()
    debugInfo(content)
    return content

def sendErrorMsgToAdmin(msg):
    sended = 0
    while 1:
        debugInfo("发送出错消息给 admin ing 。。。。。。ALARM ALARM"+msg)
        if sended ==0:
            debugInfo("真的发个短信啥的 就一次:"+msg)
            sended = 1
        time.sleep(60)
    return  ret


def getMd5(content):
    md5 = hashlib.md5(content.encode("utf-8")).hexdigest()
    return md5
def md5sum(filename):
    fd = open(filename, "r")
    fcont = fd.read().encode("utf-8")
    fd.close()
    fmd5 = hashlib.md5(fcont)
    return fmd5.hexdigest()

def clearAll(handset, screenName="screen.png"):
    debugInfo("回到待机")
    os.system(getAdbPath() +" -s  "+ str(SNO)  + " shell input keyevent KEY_HOME")
    os.system(getAdbPath() +" -s  "+ str(SNO)  + " shell input keyevent 187")


def inputABC(input, delay=2):
    os.system(getAdbPath() +" -s  "+ str(SNO)  + " shell input text " + input)
    debugInfo("输入ABC字符" + input)


def inputEnter( delay=1):
    os.system(getAdbPath() +" -s  "+ str(SNO)  + " shell input keyevent KEYCODE_ENTER " )
    debugInfo("输入回车")

def inputTabWithCount( count =1,delay=1):
    for i in range(0,count):
        os.system(getAdbPath() +" -s  "+ str(SNO)  + " shell input keyevent KEYCODE_TAB " )
        print("[" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + "]---inputTabWithCount tab :"+str(i))

def inputFkeyWithCount( fkey ,count =1,delay=1):
    for i in range(0,count):
        os.system(getAdbPath() +" -s  "+ str(SNO)  + " shell input keyevent "+fkey )
        print("[" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + "]---inputFkeyWithCount fkey :"+str(i)+" use key :"+fkey)



def clearWeixinDir():
    # print("["+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+"]---clearWeiXinDir" )
    debugInfo("清空微信目录")
    os.system(getAdbPath() +" -s  "+ str(SNO)  + " shell  rm /sdcard/tencent/MicroMsg/WeiXin/*")


def pullFromWeixinDir(localPath):
    print("[" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + "]---pullFromWeixinDir")
    # print(adbpath + currentHandsetSnumber + " shell am startservice com.qianteng.testcliper/.ClipboardService >temp2.txt")
    os.system(getAdbPath() +" -s  "+ str(SNO)  +" pull  /sdcard/tencent/MicroMsg/WeiXin/ " + localPath)

def uploadFileFromLocal(localdir, a):
    cmd = 'scp ' + localdir + a + " root@47.104.155.13:/webdata/static/img/"
    url = "http://www.maomaoyouxuan.com/static/img/" + a
    os.system(cmd)
    print(cmd)
    cmd = 'mv ' + localdir + a + ' ' + localdir + "../bak/"
    print(cmd)
    os.system(cmd)
    return url, " ", 0, 0


def taskCreate():
    debugInfo("start taskcreate","taskCreate")


def clearTaskTag():
    adbRun(" shell rm /sdcard/tasking")
    debugInfo("clearTaskTag")


def checkTask(handsetType, sno, ip="", taskresetTime=20):
    global checkType
    global SNO
    SNO = sno

    debugInfo("checknow ",sys._getframe().f_code.co_name)
    adbRun(" shell ls -l /sdcard/tasking")
    adbRun(" shell ls -l /sdcard/tasking >time.txt")
    if os.path.exists("time.txt"):

        pass
    else:
        debugInfo("no connect to devices")
        exit(1)
    with(open("time.txt", 'r')) as f:

        timeContent = f.read()
        if ("error" in timeContent):
            debugInfo("maybe error in connect devices");
        else:

            timesplit = timeContent.split(" ")
            taskTime = timesplit[-3] + " " + timesplit[-2]

    if taskTime == 'file or':
        # notask then create it now and run happy
        checkType = "run"

    else:
        # debugInfo(string_toTimestamp(taskTime))
        t = time.time()
        taskMinutes = (t - string_toTimestamp(taskTime)) / 60
        # 计算多少分钟前的任务
        taskMinutes = (math.floor(taskMinutes))

        if (taskMinutes > taskresetTime):
            checkType = "needReset"
        else:
            checkType = "needWait"

    return checkType

def isSameScreen(imgsrc, imgobj,  confidence=0.5):
    currentSize = 0
    maxSize = 0
    if not '/' in imgsrc:
        imgsrc = os.getcwd() + "/cut/" + getHandsetType() + "/" +str(SNO) + "/"+imgsrc
    if not '/' in imgobj:
        imgobj = os.getcwd() + "/cut/" + getHandsetType() + "/" +str(SNO) + "/"+imgobj

    while 1:

        time.sleep(0.1)
        if os.path.exists(imgsrc):
            #print("isSameScreen        sleep a while for  image ready"*3)
            time.sleep(0.1)
            #print(str(os.path.getsize(imgsrc)))
            maxSize = currentSize
            currentSize = os.path.getsize(imgsrc)
            if maxSize == currentSize and not maxSize == 0:
                break
        else:
            #print("no " + imgsrc)
            pass
    #print(" isSameScreen got it now  ----10" * 10)


    x,y = getRealScreenSizeXY()
    xx=int(x)/2
    yy = int(y)/2
    try:
        imsrc = ac.imread(imgsrc)
        imobj = ac.imread(imgobj)
    except:
        print("  isSameScreen  runtime error --------------------------")
        return False,0
    # find_all_sift  find_template
    # print("----------------------------isSameScreen______________________")
    # print(imgsrc)
    # print(imgobj)
    match_result = ac.find_template(imsrc,
                                    imobj)  # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
    if match_result == None:
        return False,0
    else:
        pass
    #print(match_result)
    if match_result["confidence"] > 0.9:
        ret = False
        if (match_result['result'][0] == xx and match_result['result'][1] == yy):
            ret = True
        # print("----------------isSameScreen ----------------"+str(ret))
        return ret,match_result['confidence']
    else:
        return False,0

def getTkl(tkl ):

    # if "$" in tkl:
    #     tkl = tkl.split("$")[1]
    # if "￥" in tkl:
    #     tkl = tkl.split("￥")[1]
    # if "(" in tkl:
    #     tkl = tkl.split("(")[1]
    #     tkl = tkl.split(')')[0]

    result = re.findall("[0-9A-Za-z]{11}", tkl)  # 这样更能匹配准确一丢丢
    print(result)
    if result.__len__()>0:
        tkl = result[0]

    url = 'http://www.maomaoyouxuan.com/rbt/tkl/a.php?tpwd=' + tkl
    try:
        r = requests.get(url)
        ret = r.text.split("tpwd=1")[1]
        tpwd = json.loads(ret)
        ret = tpwd['data']['tpwd']
    except:
        print("error happend")
    ret = ret.replace("￥","")
    print("新淘口令-----"+ret)
    return ret
## KEY_MENU  KEYCODE_SYSRQ  KEY_PAGE_DOWN KEY_PAGE_UP  KEYCODE_MOVE_HOME  KEYCODE_MOVE_END
#am start -a android.intent.action.VIEW -d " + urlStr
